/** *******************************************************************
 * FlexDatabaseManager
 * Copyright (c) 2008 Jonnie Spratley. All Rights Reserved.
 * @author  Jonnie Spratley
 * @contact jonniespratley@gmail.com
 * @internal
 ******************************************************************* */
package com.jonniespratley.flexdatabasemanager.commands.databases
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.adobe.serialization.json.JSON;
	import com.jonniespratley.flexdatabasemanager.business.FlexDatabaseManagerDelegate;
	import com.jonniespratley.flexdatabasemanager.events.databases.GetDatabasesEvent;
	import com.jonniespratley.flexdatabasemanager.model.ModelLocator;
	import com.jonniespratley.flexdatabasemanager.vo.*;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	public class GetDatabasesCommand implements ICommand, IResponder
	{
		private var model:ModelLocator = ModelLocator.getInstance();

		public function execute( event:CairngormEvent ) : void
		{
			model.interactingWithServer = true;
			
			var evt:GetDatabasesEvent = event as GetDatabasesEvent;
			
			var delegate:FlexDatabaseManagerDelegate = new FlexDatabaseManagerDelegate( this );
				delegate.getDatabases( model.currentUser );														 	
		}
		
		public function result( data:Object ) : void
		{
			model.interactingWithServer = false;
			
			var resultEvt:ResultEvent = data as ResultEvent;
			if ( resultEvt.result is String )
			{
				var rawData:String = String( resultEvt.result ); 
				var jsonArray:Array = ( JSON.decode( rawData ) as Array );
				
				var tempArray:Array = new Array();
				
				for ( var s:String in jsonArray )
				{		
					tempArray.push( new DatabaseVO( jsonArray[s] ) );	
				}
				model.databaseCollection = new ArrayCollection( tempArray );
			}
			
		}

		public function fault( fault:Object ):void
		{
			model.interactingWithServer = false;
			
			var faultEvt:FaultEvent = fault as FaultEvent;
			Alert.show(faultEvt.fault.toString(), "Error");
			trace(faultEvt.fault.faultString);
		}

	}
}
